/**
 * @date     2018-11-07
 * @author   尹学江
 */
import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { binaryParser } from '@/utils/tools'
// api 的 base_url
const baseURL = process.env.NODE_ENV === 'development' ? '/api' : ''

// 创建axios实例
const service = axios.create({
  baseURL,
  timeout: 60 * 1000,
  headers: { 'Content-Type': 'application/json' }
})

// request 拦截器
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (store.getters.token) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers.token = store.getters.token
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  async response => {
    let res = response.data
    if (response.request.responseType === 'blob') { // 文件二进制流响应全部数据（PS:文件名在请求头中）
      res = await binaryParser(response)
    }
    if (res.code === '1005' || res.code === '1006' || res.code === '1000') {
      console.log('用户没有权限或token失效！')
      store.dispatch('frontLogout').then(() => {
        Message.error(res.message || '验证失败，请重新登录!')
        window.location.href = '/#/login'
      })
    } else if (res.code !== '0000' && res.message) {
      // 弹警告信息
      Message({ message: res.message, type: 'warning' })
    }
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

/**
 * 发送ajax请求
 * @param    {String}  url     地址
 * @param    {String}  method  请求方式 get post put delete
 * @param    {Object}  data    参数对象
 * @param    {Object}  ctx 参数
 */
const callApi = (url, method, data, ctx) => {
  if (process.env.NODE_ENV === 'development') {
    // 开发环境
    if (url.indexOf('?') > -1) {
      url += '&t=' + Math.random()
    } else {
      url += '?t=' + Math.random()
    }
  }
  return service(
    Object.assign(
      {},
      {
        url: `${url}`,
        method,
        params: method === 'get' ? data : {},
        data: method !== 'get' ? data : {},
        withCredentials: false
      },
      ctx
    )
  )
}

/**
 * 请求接口
 * @param url 接口地址
 * @param data 接口参数
 * @param ctx 所有请求参数
 */
export const getApi = (url, data = {}, ctx = {}) => callApi(url, 'get', data, ctx)
export const postApi = (url, data = {}, ctx = {}) => callApi(url, 'post', data, ctx)
export const putApi = (url, data = {}, ctx = {}) => callApi(url, 'put', data, ctx)
export const deleteApi = (url, data = {}, ctx = {}) => callApi(url, 'delete', data, ctx)

/**
 * 上传请求地址
 * @param url 上传地址
 */
export const upLoadApi = url => baseURL + url

/**
 * 添加基本地址
 * @param url 地址
 */
// console.log(window.location.origin)
export const addBaseURL = url => baseURL + url
